﻿using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
using System;
using System.Configuration;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Delegen.TfsWorkspaceRemover
{
    class WorkspaceRemover
    {
        System.Diagnostics.EventLog appLog;
        private TfsTeamProjectCollection _server;
        private VersionControlServer sourceControl; 

        public WorkspaceRemover(TfsTeamProjectCollection server)
        {
            appLog = new System.Diagnostics.EventLog("Application");

            appLog.Source = "TfsWorkspaceRemover";
            appLog.WriteEntry("TfsWorkspaceRemover Start...");

            _server = server;
            sourceControl = (VersionControlServer)_server.GetService(typeof(VersionControlServer));
            
            
        }

        public void Remove()
        {
            try
            {
                //Get the name of the machine & User the app is running from or from configuration file
                var user = string.IsNullOrEmpty(ConfigurationManager.AppSettings["User"]) ? Environment.UserDomainName + @"\" + sourceControl.AuthenticatedUser : ConfigurationManager.AppSettings["User"];
                var host = string.IsNullOrEmpty(ConfigurationManager.AppSettings["HostMachine"]) ? System.Net.Dns.GetHostName().ToString() : ConfigurationManager.AppSettings["HostMachine"];                
                Workspace[] wss = sourceControl.QueryWorkspaces(null, user, host);

                var lastAccessDate = string.IsNullOrEmpty(ConfigurationManager.AppSettings["LastAccessDays"]) ? 0 : Convert.ToDouble(ConfigurationManager.AppSettings["LastAccessDays"]);

                foreach (var ws in wss)
                {
                    //Check last access date to workspace
                    if (DateTime.Now >= ws.LastAccessDate.AddDays(lastAccessDate))
                    {
                        //Microsoft had a bug when removing the workspace without removing the mapping
                        foreach (var folder in ws.Folders)
                        {
                            if (!folder.IsCloaked)
                            {
#if !DEBUG
                                ws.DeleteMapping(folder);

                                var di = new DirectoryInfo(folder.LocalItem);
                                setAttributesNormal(di);
                                di.Delete(true);
#endif
                            }
                        }
#if !DEBUG
                        ws.Delete();
#endif
                        appLog.WriteEntry("TfsWorkspaceRemover Start...",EventLogEntryType.Information);
                        
                        appLog.WriteEntry("Workspace deleted: " + ws.Name + "\nUsername: " + ws.OwnerName + "\nLast Access Date : " + ws.LastAccessDate.ToString(), EventLogEntryType.Information);
                    }
                }                
                appLog.WriteEntry("TfsWorkspaceRemover End!", EventLogEntryType.Information);
            }
            catch (Exception ex)
            {                
                appLog.WriteEntry("ERROR: " + ex.Message, EventLogEntryType.Error);
            }
        }

        private void setAttributesNormal(DirectoryInfo di)
        {
            foreach (var subDir in di.GetDirectories())
            {
                setAttributesNormal(new DirectoryInfo(subDir.FullName));
            }
            foreach (var filePath in di.GetFiles())
            {
                var file = new FileInfo(filePath.FullName);
                file.Attributes = FileAttributes.Normal;
            }

        }

    }
}
